package gl.android.biyiqing.competent;


import gl.adapter.BaseFragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class TabViewPager implements OnCheckedChangeListener,
		OnPageChangeListener {
	private ViewPager mViewPager;
	private RadioGroup mRadioGroup;
	private Fragment context;
	private ArrayList<Fragment> fragments;

	/**
	 * 一个viewpager 滑动状态 指示器
	 * 
	 * @param context
	 * @param mViewPager
	 * @param mRadioGroup
	 * @param cursor
	 *          
	 */
	public TabViewPager(Fragment context, ViewPager mViewPager,
			RadioGroup mRadioGroup, ArrayList<Fragment> fragments) {
		this.context = context;
		this.mViewPager = mViewPager;
		mViewPager.setOnPageChangeListener(this);
		this.mRadioGroup = mRadioGroup;
		mRadioGroup.setOnCheckedChangeListener(this);
		this.fragments = fragments;
		Init();

	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		mViewPager.setCurrentItem(getIndexInRadioGroup(group, checkedId));
	}

	public static int getIndexInRadioGroup(RadioGroup group, int checkedId) {
		int index = 0;
		for (int i = 0; i < group.getChildCount(); i++) {
			if (checkedId == group.getChildAt(i).getId()) {
				index = i;
			}
		}
		return index;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	private void Init() {
		mViewPager.setAdapter(new BaseFragmentPagerAdapter(context
				.getChildFragmentManager(), fragments));
	}

	@Override
	public void onPageSelected(int arg0) {
		((RadioButton) mRadioGroup.getChildAt(arg0)).setChecked(true);

	}
}
